import sys
from time import sleep


def vote(wd, user, sticket, data):
    print("选择站点，时间")
    # 车票状态
    status = True
    # 点击首页
    select(wd, data[15]).click()

    # 出发地
    from_station = select(wd, data[16])
    from_station.click()
    from_station.send_keys(sticket["出发地"])
    # 获取当前车站地点搜索列表
    search_list = select(wd, data[18])
    areas = select(search_list, data[19], True)
    for area in areas:
        if area.text == sticket["出发地"]:
            # 点击地点
            area.click()
            break

    # 到达地
    to_station = select(wd, data[17])
    to_station.click()
    to_station.send_keys(sticket["到达地"])
    # 获取当前车站地点搜索列表
    search_list = select(wd, data[18])
    areas = select(search_list, data[19], True)
    for area in areas:
        if area.text == sticket["到达地"]:
            # 点击地点
            area.click()
            break

    # 出发日期
    time = select(wd, data[20])
    time.click()
    time.clear()
    # 关闭日历
    select(wd, data[21]).click()
    time.send_keys(sticket["出发日期"])

    # 获取当前窗口句柄
    search_windows = wd.current_window_handle

    # 查询
    select(wd, data[22]).click()

    # 获得当前所有打开的窗口的句柄
    all_handles = wd.window_handles
    # 进入注册窗口
    for handle in all_handles:
        if handle != search_windows:
            # 切换窗口
            print("切换操作窗口")
            wd.switch_to.window(handle)

    # 车票页面确认提示按钮
    select(wd, data[23]).click()

    # 获取当前页面车票列表
    print("获取当前页面车票列表")
    try:
        tickets_tbody = select(wd, data[24], True)
        tran = select(tickets_tbody[0], data[25], True)
        tran_list = len(tran)
    except Exception as e:
        # print(e)
        print("获取元素异常")
        print("请稍等，正在重新获取元素")
        sleep(3)
        tickets_tbody = select(wd, data[24], True)
        tran = select(tickets_tbody[0], data[25], True)
        tran_list = len(tran)

    for tr in range(tran_list):
        if tran[tr].text == sticket["车次"]:
            try:
                # 点击预定
                if tran[tr + 1].text == "预订":
                    tran[tr + 1].click()
                    status = False
                    break
                else:
                    print("此车次无票，请修改车次")
                    sys.exit(0)
            except IndexError as e:
                print("此车次无票，请修改车次")
                sys.exit(0)

    # 判断是否有车票
    if status:
        print("页面无此车票，请修改车次")
        sys.exit(0)

    # 判断当前是否在测试
    if __name__ == "__main__":
        # 登录
        login(driver, user, data)
        # 验证码
        verificationCode(driver, data)

    # 获取乘车人列表
    print("获取乘车人列表")
    ul = select(wd, data[26])
    lis = select(ul, data[27], True)
    people_list = sticket["乘车人"].split(",")
    for li in lis:
        for people in people_list:
            if li.text == people:
                # 点击乘车人
                li.click()

    # 点击提交订单
    select(wd, data[28]).click()
    print("点击提交订单")
    sleep(1)
    # 点击返回修改
    select(wd, data[29]).click()
    print("点击返回修改")


# 以下为模块测试代码
if __name__ == "__main__":
    print("test_buyTickets")
    from selenium import webdriver
    import readcsv as Csv
    import readjson as Json
    from selector import select
    from login import login, verificationCode

    try:
        user = Json.read("../config/user.json")
        data = Csv.read("../config/data.csv")
        ticket = Json.read("../config/ticket.json")
        # 避免webdriver检测
        options = webdriver.ChromeOptions()
        options.add_argument('--disable-blink-features=AutomationControlled')
        options.add_experimental_option('excludeSwitches', ['enable-automation'])
        driver = webdriver.Chrome(options=options)
        # 设置隐式等待为10秒
        driver.implicitly_wait(5)
        print("打开12306网站")
        # 打开12306网站
        driver.get("https://www.12306.cn/")
        # 设置浏览器全屏
        driver.maximize_window()
        # 购票
        vote(driver, user, ticket, data)
    except Exception as e:
        print(e)
    finally:
        # 退出浏览器
        driver.quit()
        print("程序退出")
        sleep(2)
else:
    from tools.selector import select